import type { Form } from "@/interface/formData";
import { ElMessage, ElMessageBox, type FormMetaProps, type TableInstance } from "element-plus";
import { useUserStore } from "@/stores/userStore";
import { storeToRefs } from "pinia";
import { computed, ref } from "vue";
import formData from "@/tool/data/formData";
import axios from "axios";



export default function () {


      const userStore = useUserStore();
      const { useridentityfer, username_store } = storeToRefs(userStore);

      //请求后端======================================================================

      function getTableData() {
            return axios.get("/api/institute/works")
                  .then(response => {
                        if (response.data.code === 200) {
                              console.log("请求中的数据:: ", response.data.data);
                              return response;
                        }
                  })
                  .catch(error => {
                        ElMessage.error("请求失败");
                  })
      }

      function rejectOne(id: number, msg: any) {
            axios.get(`/api/institute/reject/${id}/${useridentityfer.value}/${msg}`)
                  .then(response => {
                  })
                  .catch(error => {
                        ElMessage.info("请求失败");
                  })
      }


      function accessOne(id: number) {
            axios.get(`/api/institute/access/${id}/${useridentityfer.value}`)
                  .then(response => {
                  })
                  .catch(error => {
                        ElMessage.info("请求失败");
                  })
      }

      function requestRejectAll(idlist: number[], msg: any) {
            axios.get(`/api/institute/rejectAll/${idlist}/${useridentityfer.value}/${msg}`)
                  .then(response => {
                        response;
                  })
                  .catch(error => {
                        ElMessage.info("请求失败");
                  })
      }


      function requestAccessAll(IdList: number[]) {
            axios.get(`/api/institute/accessAll/${IdList}/${useridentityfer.value}`)
                  .then(response => {
                  })
                  .catch(error => {
                        ElMessage.info("请求失败");
                  })
      }


      //筛选框==========================================================================

      let userName = ref("");
      let status = ref("");
      let title = ref("");
      const flitItem = ref({ userName, status, title });

      function removeRowsByIds(){
            const selectedIds = multipleSelection.value.map(item => item.id);
            formarTable.value = formarTable.value?.filter(item => !selectedIds.includes(item.id))
      }

      async function accessAll() {
            if (multipleSelection.value.length <= 0) {
                  ElMessage.warning("请选择需要通过的数据")
            } else {
                  const IdList: number[] = []
                  await multipleSelection.value.filter((item) => {
                        console.log("选择职位", item);
                        IdList.push(item.id);
                  });
                  await requestAccessAll(IdList);
                  removeRowsByIds();
            }


      }

      async function rejectAll() {
            if (multipleSelection.value.length <= 0) {
                  ElMessage.warning("请选择需要驳回的数据")
            } else {
                  const IdList: number[] = []
                  await multipleSelection.value.filter((item) => {
                        console.log("选择职位", item);
                        IdList.push(item.id);
                  });
                  console.log("IdS::" + IdList);
                  const rejectReasonValue = await rejectReason(); // 等待用户输入
                  await requestRejectAll(IdList, rejectReasonValue);
                  removeRowsByIds();
            }

      }

      //侧边栏==================================================================================

      const drawer = ref(false); //侧边栏显示标志

      //下拉框数据
      let optionItem = ref({
            selectedValue: "",
            option: [
                  { value: "1", label: "零工" },
                  { value: "2", label: "短期兼职" },
                  { value: "3", label: "长期兼职" }
            ]
      });

      let isEdit = ref({
            userName: false,
            status: false,
            title: false,
            description: false,
            price: false,
            taker: false,
            createdTime: false,
            startTime: false,
            publishTime: false,
            jobType: false,
            autoPublish: false,
      }); //控制表单内容是否可编辑

      //表单不可编辑
      function formUnEdit() {
            isEdit.value.createdTime = false;
            isEdit.value.startTime = false;
            isEdit.value.price = false;
            isEdit.value.userName = false;
            isEdit.value.description = false;
            isEdit.value.status = false;
            isEdit.value.taker = false;
            isEdit.value.title = false;
            isEdit.value.autoPublish = false;
      }


      const currentRowData = ref<Form>({
            //存储一条数据的变量
            id: 0,
            userIdentifier:0,
            userName: "",
            jobType: "",
            status: "",
            title: "",
            maxPeople: 0,
            description: "",
            salary: 0,
            process: "",
            takersId: [],
            takersName: [],
            createdTime: new Date(),
            startTime: new Date(),
            endTime: new Date(),
            publishTime: new Date(),
            autoPublish: true,
      });

      //表单清空
      function clearForm() {
            currentRowData.value = {
                  id: 0,
                  userIdentifier:0,
                  userName: "",
                  jobType: "",
                  status: "",
                  title: "",
                  maxPeople: 0,
                  description: "",
                  salary: 0,
                  process: "",
                  takersId: [],
                  takersName: [],
                  createdTime: new Date(),
                  startTime: new Date(),
                  endTime: new Date(),
                  publishTime: new Date(),
                  autoPublish: true,
            };
      }

      function drawerClose() {
            drawer.value = false;
            clearForm();
      }
      //用于刷新侧边栏
      const drawerKey = ref(0);
      //侧边栏步骤
      const step = ref<any>(0);
      //步骤设置
      const stepSet = (num: any) => {
            ElMessage.info("订单进度：" + num);
            if (num === null) {
                  step.value = null;
            } else {
                  step.value = num;
            }
            if (num == 4 || num == 5) {
                  drawerKey.value++;
            }
      };


      const steps = ref({
            drawerKey: drawerKey,
            step: step,
            stepSet: stepSet,
      });

      const removeRowById = (id:number) => {
            const index = FlitTableData.value?.findIndex(item => item.id === id)
            if (index !== -1){
                  FlitTableData.value?.splice(index as number,1)
            }
          }


      function accessTableOne(row?: Form, $event?: any) {
            if (row != null) {
                  event?.stopPropagation();
                  ElMessage.info(row.title + "" + row.id)
                  accessOne(row.id);
                  removeRowById(row.id);
            }
      }

      function accessDrawnOne() {
            if (currentRowData.value.id != 0 || currentRowData.value.id != null) {
                  ElMessage.info(currentRowData.value.title);
                  let wordId = currentRowData.value.id;
                  accessOne(wordId);
                  removeRowById(wordId);
            }
      }

      function rejectReason(wordId?: number) {
            return new Promise((resolve, reject) => {
                  ElMessageBox.prompt('请输入驳回理由', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                  })
                        .then(({ value }) => {
                              ElMessage.info("订单：" + wordId + " 的驳回理由：" + value);
                              resolve(value);  // 将值返回
                        })
                        .catch(() => {
                              ElMessage({
                                    type: 'info',
                                    message: 'Input canceled',
                              });
                              reject("");  // 取消时返回空
                        });
            });
      }

      async function rejectTableOne(row?: Form, $event?: any) {
            if (!row) return;
            $event?.stopPropagation();

            try {
                  const rejectValue = await rejectReason(row.id); // 等待用户输入
                  console.log("rejectValue:", rejectValue);

                  if (rejectValue) {
                        await rejectOne(row.id, rejectValue); // 只有用户输入后才发送请求
                        removeRowById(row.id);
                  } else {
                        console.log("用户取消了输入，未发送请求");
                  }
            } catch (error) {
                  console.log("取消驳回或发生错误");
            }

      }

      async function rejectDrawnOne() {
            // debugger
            let wordId = 0;
            wordId = currentRowData.value.id;

            try {
                  const rejectValue = await rejectReason(wordId);
                  if (rejectValue) {
                        await rejectOne(wordId, rejectValue); // 只有用户输入后才发送请求
                        removeRowById(wordId);
                  } else {
                        console.log("用户取消了输入，未发送请求");
                  }
            } catch {
                  console.log("取消驳回或发生错误");
            }
            initTable();

      }

      // 侧边栏提交方法
      const handleSubmit = async () => {
            try {
                  const newRow = {
                        ...currentRowData.value, // 保留当前输入的值
                        userIdentifier: useridentityfer.value,//用户编号
                        status: "1",//职位状态
                        jobType: optionItem.value.selectedValue,//职位类型
                  };
            } catch (error) {
                  console.error("添加失败", error);
            }
      };
      //表格====================================================================================
      const form = formData();
      let tableData = ref<Form[]>([]);
      let formarTable = ref<Form[]>();

      const FlitTableData = computed(() => {
            if (!status.value && !userName.value && !title.value)
                  return formarTable.value;
            return formarTable.value?.filter((item: Form) => {
                  const matchStatus = status.value
                        ? item.status.includes(status.value)
                        : true;
                  const matchPublisher = userName.value
                        ? item.userName.includes(userName.value)
                        : true;
                  const matchTitle = title.value
                        ? item.title.includes(title.value)
                        : true;

                  // console.log("FlitTableData",FlitTableData)
                  return matchStatus && matchPublisher && matchTitle;
            });
      });

      function formatTableData(data: Form[]) {
            formarTable.value = data.map((item) => ({
                  ...item,
                  status: item.status === "1" ? "待审核" :
                        item.status === "2" ? "审核通过" :
                              item.status === "3" ? "审核失败" : item.status,

                  process: item.process === "1" ? "待接取" :
                        item.process === "2" ? "已接取" :
                              item.process === "3" ? "进行中" :
                                    item.process === "4" ? "已完成" :
                                          item.process === "5" ? "已结算" : item.process,

                  jobType: item.jobType === "1" ? "零工" :
                        item.jobType === "3" ? "短期兼职" :
                              item.jobType === "2" ? "长期兼职" : item.jobType,

                  autoPublish: item.autoPublish,
            }))
      }



      async function initTable() {
            const response = await getTableData();
            tableData.value = response?.data?.data; // 先获取 data
            if (tableData.value) { // 确保 data 不为空
                  formatTableData(tableData.value);
            }
      }

      //=========行点击函数，打开侧边栏===============
      const RowClick = (row: Form) => {
            currentRowData.value = { ...row }; //复制数据
            console.log("currentRowData: ", currentRowData.value);
            formUnEdit(); //表单不可编辑
            if (row.process == "待接单") {
                  stepSet(0);
            }
            if (row.process == "已接单") {
                  stepSet(1);
            }
            if (row.process == "经行中") {
                  stepSet(2);
            }
            if (row.process == "已完成") {
                  stepSet(3);
            }
            if (row.process == "已结算") {
                  stepSet(4);
            }
            if (row.process == null || row.process == "") {
                  stepSet(null);
            }
            drawer.value = true; //显示侧边栏
      };

      //价格的格式化展示
      const formatPrice = (row: Form, column: Form, cellValue: number) => {
            return `${cellValue}元/小时`;
      };

      //  表格复选框===============
      const multipleSelection = ref<Form[]>([]);
      const handleSelectChange = (val: Form[]) => {
            multipleSelection.value = val;
            console.log("选中的兼职：",multipleSelection.value)
      };
      const selectable = (row: Form) => !([] as number[]).includes(row.id);
      let multipBox = ref({
            selectable: selectable,
            handleSelectChange: handleSelectChange
      })


      //审核通过/驳回的方法
      const instituteFunction = {
            rejectTableOne: rejectTableOne,
            rejectDrawnOne: rejectDrawnOne,
            accessDrawnOne: accessDrawnOne,
            accessTableOne: accessTableOne,
            rejectAll: rejectAll,
            accessAll: accessAll,
      }
      return {
            drawer,
            flitItem,
            steps,
            FlitTableData,
            formatPrice,
            multipBox,
            RowClick,
            currentRowData,
            isEdit,
            optionItem,
            handleSubmit,
            initTable,
            rejectAll,
            instituteFunction,
            drawerClose,
      }
}